// 实现这个项目的构建任务
const { src, dest, series, parallel, watch } = require("gulp");
const swig = require('gulp-swig');
const sass = require("gulp-sass");
const babel = require("gulp-babel");
const imagemin = require("gulp-imagemin");
const htmlmin = require("gulp-htmlmin");
const uglify = require("gulp-uglify");
const cleanCss = require("gulp-clean-css");
const gulpif = require("gulp-if");
const del = require('del');
const useref = require("gulp-useref");
const browserSync = require('browser-sync'); // 自动热更新
const rename = require("gulp-rename");
const pkg = require("./package.json");

const bs = browserSync.create();

const css = () => {
    return src("src/assets/styles/*.scss", { base: "src" })
    .pipe(sass({ outputStyle: 'expanded' }))
    .pipe(dest("temp"));
}

const html = () => {
    console.log("html")
    return src("src/*.html", { base: "src" })
    .pipe(swig({ 
        data: {
            pkg
        },
        defaults: { cache: false }
     }))
    .pipe(rename({ external: ".html" }))
    .pipe(dest("temp"))
}

const script = () => {
    return src("src/assets/scripts/*.js", { base: "src" })
    .pipe(babel({ presets: ["@babel/preset-env"] }))
    .pipe(dest("temp"));
}

const font = () => {
    return src("src/assets/fonts/**", { base: "src" }).pipe(imagemin()).pipe(dest("dist"));
}

const image = () => {
    return src("src/assets/images/**", { base: "src" }).pipe(imagemin()).pipe(dest("dist"));
}

const setuseref = () => {
    return src("temp/**/*", { base: "temp" })
    .pipe(useref({ searchPath: ["temp", "."] }))
    .pipe(gulpif("*.js", uglify())) // 不要用正则匹配,否则无法压缩
    .pipe(gulpif("*.css", cleanCss())) // 不要用正则匹配,否则无法压缩
    .pipe(gulpif("*.html", htmlmin( { collapseWhitespace: true, minifyCSS: true, minifyJS: true } ))) // 不要用正则匹配,否则无法压缩
    .pipe(dest("dist"));
}

const extra = () => {
    return src("public/**", { base: "public" }).pipe(dest("dist"))
}

const clean = () => {
    return del(['temp', 'dist']);
}

const serve = () => {
    // 监听以下文件变化自动更新
    watch("src/assets/styles/*.scss", css);
    watch("src/assets/scripts/*.js", script);
    watch("src/**/*.html", html);
    // 开发阶段不需要编译这些,无损压缩的图片和文件
    // watch("src/assets/images/**", image);
    // watch("src/assets/fonts/**", font);
    // watch("public/**", extra);
    bs.init({
        notify: false, // 是否提示
        port: 2020,
        open: false, // 自动打开浏览器
        files:  "temp/**", // 哪些文件改变后浏览器自动更新
        server: {
            // baseDir: "temp",
            baseDir: ["temp", "src", "public"], // 一次从前往后找
            // 优先于 baseDir
            routes: {
                "/node_modules": "node_modules"
            }
        }
    })
}

const compile = parallel(css, script, html);

const build = series(clean, compile, font, image, extra, setuseref);

const dev = series(compile, serve);

module.exports = {
    clean,
    dev,
    build
}